package com.sky.jwt;

import com.sky.constant.PasswordConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

/**
 * JWT 测试方法
 */
public class JwtTest {
    /**
     * 生成jwt令牌
     */
    @Test
    public void getJwt(){
        //设置载荷
        HashMap<String, Object> claims=new HashMap<>();
        claims.put("id",1L);
        claims.put("username","zhp");
        //生成令牌
        String jwt = Jwts.builder()
                .setClaims(claims)//设置载荷
                .signWith(SignatureAlgorithm.HS256, "ithaipeng")//设置加密算法和前面
                .setExpiration(new Date(System.currentTimeMillis() + 3600 * 1000 * 2))//设置过期时间
                .compact();
        System.out.printf(jwt);
    }

    /**
     * 解析token
     */
    @Test
    public void parserJwt(){
        Claims claims = Jwts.parser()
                .setSigningKey("ithaipeng")
                .parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxNzAyODI4Nzc2LCJ1c2VybmFtZSI6InpocCJ9.rKv2aZQqoDPu9VofbRNYAEGHiOYqKnmF3kP9YNEtdmQ")
                .getBody();
        Long id = claims.get("id", Long.class);
        System.out.println(id);
    }
/**
 * md5代码加密
 */
    @Test
    public void md5(){
        String s = DigestUtils.md5DigestAsHex(PasswordConstant.PASSWORD_CONSTANT.getBytes());
        System.out.println(s);
    }
}
